package com.lzw.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.lzw.bean.Node;
import com.lzw.common.bean.Result;
import com.lzw.common.controller.BaseController;
import com.lzw.common.service.impl.CommonService;
import com.lzw.param.node.Page;
import com.lzw.service.NodeService;
import com.lzw.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by 林志伟 on 2017/5/11.
 */
@Controller()
@RequestMapping("/node")
public class NodeController extends BaseController {
    @Autowired
    NodeService nodeService;




    @GetMapping("/index")
    public String  index(Model model, Page page){
        PageInfo pageInfo= nodeService.page(page);
        logger.info("节点列表："+ JSON.toJSONString(pageInfo));
        model.addAttribute("pageInfo",pageInfo);
        return this.getTemplateName();
    }

    @GetMapping("/add")
    public String add(){
        return this.getTemplateName();
    }

    @PostMapping("/add")
    @ResponseBody
    public Result addPost(@Valid Node node, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
//            logger.info("验证错误："+bindingResult.getFieldError().getDefaultMessage());
            return CommonService.error(bindingResult.getFieldError().getDefaultMessage());
        }
        System.out.println("传入role:"+node.toString());
        Result result=nodeService.insert(node);
        return result;
    }

    @GetMapping("/update")
    public String update(@RequestParam int id, Model model){
        com.lzw.bean.Node node =nodeService.find(id);
        model.addAttribute("node",node);
        return this.getTemplateName();
    }

    @ResponseBody
    @PostMapping("/update")
    public Result updatePost(Node node, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return CommonService.error(bindingResult.getFieldError().getDefaultMessage());
        }
        return nodeService.update(node);
    }

    @PostMapping("/delete")
    @ResponseBody
    public  Result delete(@RequestParam("id[]") int[] ids){
        for (int i=0;i<ids.length;i++){
            logger.info("删除ids:"+ids[i]);
        }
        return  nodeService.deleteAll(ids);
    }


    /**
     * 启用
     * @param id
     * @return
     */
    @PostMapping("/open")
    @ResponseBody
    public Result open(@RequestParam("id") int id){

        return  nodeService.open(id);
    }


    /**
     * 禁用
     * @param id
     * @return
     */
    @PostMapping("/close")
    @ResponseBody
    public Result close(@RequestParam("id") int id){

        return  nodeService.close(id);
    }
}
